using System;
using System.Collections;
using System.Xml;
using Flaschengeist;
using Flaschengeist.DataAccess;
using Flaschengeist.Views;
using UnityEngine;

namespace Flaschengeist.Processes 
{
	public class LoadLevelCount : MonoBehaviour
	{
		private XmlRpc xmlrpc;
		private ErrorView errorView;
		
		public void Start()
		{	
			errorView = gameObject.GetComponent<ErrorView>();
			xmlrpc = gameObject.AddComponent<XmlRpc>();
			xmlrpc.Completed += LoadCompleted;
		}
		
		private void LoadCompleted(string xml)
		{
			var levelCount = 0;
			
			foreach (XmlNode node in xml.GetRecord())
			{
				if (node.HasChildNodes)
				{
					if(node.FirstChild.InnerText == "LevelCount")
						levelCount = Int32.Parse(node.LastChild.GetValueFromNode());	
				}
			}
			Completed(levelCount);
		}	
		
		public void Process()
		{
			try
			{
				Debug.Log("Start load levelCount");
				xmlrpc.Process("getLevelCount", new Hashtable());
			}
			catch(Exception ex)
			{
				errorView.Show(ex);
			}
		}
		
		public event Action<int> Completed;
	}
}